<?php
/**
 * Created by PhpStorm.
 * User: wangkxin@foxmail.com
 * Date: 2022/7/27
 * Time: 11:20
 * 实现的消息实时推送功能 ajax 反推
 */

namespace app\index\controller;


use app\BaseController;
use think\facade\View;

class LongPolling extends BaseController
{
    //视图
    public function index()
    {
        return View::fetch();
    }

    //发送数据 ,长轮询推送 ajaxPush.php
    public function ajaxPush()
    {
        $filename = public_path().'/Long/data.txt';
        $isread_file = public_path().'/Long/isread.txt';
        $userfile = public_path().'/Long/user.txt';
        $get_user = $_GET['user'] == '1' ? '2' : '1';
        $msg = '';
        while(1){
            $msg = file_get_contents($filename);
            $isread = file_get_contents($isread_file);
            $user = file_get_contents($userfile);
            //是对方发送的消息，设置消息已读，退出循环。
            if($isread == '0' && $get_user == $user){
                file_put_contents($isread_file,'1');
                break;
            }
            sleep(1);
        }
        return json(['msg'=>$msg]);
    }

    //处理输入,输入数据库
    public function writetxt()
    {
        $filename = public_path().'/Long/data.txt';
        $isread_file = public_path().'/Long/isread.txt';
        $user = public_path().'/Long/user.txt';
        //写入消息, 消息未读,谁发送的消息
        file_put_contents($filename,$_GET['msg']);
        file_put_contents($isread_file,'0');
        file_put_contents($user,$_GET['user']);
        return json(array('sf'=>true));
    }





}